package 算法回顾;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-09-20
 **/

public class No1143最长公共子序列 {

    public int longestCommonSubsequence(String text1, String text2) {
        int[][] dp = new int[text1.length()][text2.length()];
        char[] arr1 = text1.toCharArray();
        char[] arr2 = text2.toCharArray();

        // base
        for (int i = 0; i < arr2.length; i++) {
            if (arr1[0] == arr2[i]) {
                for (int j = i; j < arr2.length; j++) {
                    dp[0][j] = 1;
                }
                break;
            }
        }
        for (int i = 0; i < arr1.length; i++) {
            if (arr2[0] == arr1[i]) {
                for (int j = i; j < arr1.length; j++) {
                    dp[j][0] = 1;
                }
                break;
            }
        }

        for (int i = 1; i < text1.length(); i++) {
            for (int j = 1; j < text2.length(); j++) {
                if (arr1[i] == arr2[j]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                }
                dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);
                dp[i][j] = Math.max(dp[i][j], dp[i][j - 1]);
            }
        }

        return dp[text1.length() - 1][text2.length() - 1];
    }

    public static void main(String[] args) {
        No1143最长公共子序列 n = new No1143最长公共子序列();
        String text1 = "abcde";
        String text2 = "ace";
        int result = n.longestCommonSubsequence(text1, text2);
        System.out.println(result);
    }

}
